package com.tanhua.sso.controller;

import com.tanhua.common.pojo.User;
import com.tanhua.sso.service.UserService;
import com.tanhua.sso.vo.ErrorResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/loginVerification")
    private ResponseEntity<Object> login(@RequestBody Map<String, String> param) {
        String phone = param.get("phone");
        String code = param.get("verificationCode");
        String data = userService.login(phone, code);

        if (StringUtils.isNotEmpty(data)) {
            String[] split = StringUtils.split(data, "|");
            Map<String, Object> result = new HashMap<>();
            result.put("token", split[0]);
            result.put("isNew", Boolean.valueOf(split[1]));
            return ResponseEntity.ok(result);
        }
        ErrorResult errorResult = ErrorResult.builder().errCode("000002").errMessage("登陆失败!").build();
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResult);
    }

    @GetMapping("{token}")
    public User queryUserByToken(@PathVariable("token") String token) {
        return userService.queryUserByToken(token);
    }

}
